//register
var router =require('express').Router();
var User=require('../model/user');
var captcha=require('../lib/captcha');

module.exports = router;
router.get('/',(req, res)=>{
    var regCache=req.session.regCache;
    delete req.session.regCache;
    res.render('register',{
        title:'Register',
        regCache:regCache,
        flash:{
            success:req.flash('success').toString(),
            error:req.flash('error').toString()
        },
        captcha:captcha()
    });
});

router.post('/',(req,res,next)=>{
    var name=req.body.name,password=req.body.password,repeat=req.body.repeat;
    if(!(/^13\d{9}$/.test(name) || /\w+@\w+\.\w+/.test(name))){
        req.flash('error','用户名格式不正确！');
        req.session.regCache={name:name};
        return res.redirect('back');
    }

    if(!(/^\w{6,}$/.test(password) || password!==repeat)){
        req.flash('error','密码非法或两次输入不一致！');
        req.session.regCache={name:name};
        return res.redirect('back');
    }

    User.findOne({name:name},(err, doc)=>{
        if(err)return next(err);

        if(doc){
            req.flash('error','用户名已注册！');
            req.session.regCache={name:name};
            return res.redirect('back');
        }
        new User({
            name:name,
            password:password,
            regDate:new Date(),
        }).save((err)=>{
                if(err)return next(err);
                req.session.loginCache={name:name};
                res.redirect('/login');
        });
    });

});

